/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package device

import (
	"context"
	"fmt"
	"fpga-vboard/pins"
	"time"
)

func init() {
	config := &RealTimerConfig{
		DeviceInfo: DeviceInfo{
			Id:        RTC_DEFAULT,
			Type:      RTC,
			InputPins: nil,
			Name:      "Real Time Clock",
			OutputPins: []*pins.PinDef{
				{
					Name:      "default_rtc",
					BitSize:   1,
					Direction: pins.PinDirectionOutput,
				},
			},
			IsOptional: true,
			Enable:     false,
		},
		TimerClockFrequency: 100,
	}
	RegisterDev(config)
}

type RealTimeClock struct {
	*DeviceBase
	Frequency int64
	nextTick  time.Time
	curStatus bool
}

func NewRealTimeClock(config *RealTimerConfig) *RealTimeClock {
	return &RealTimeClock{
		DeviceBase: &DeviceBase{
			Config: config,
		},
		Frequency: config.TimerClockFrequency,
		curStatus: true,
	}
}

func (rtc *RealTimeClock) Run(ctx context.Context) {
	if rtc.nextTick.Before(time.Now()) {
		// fmt.Printf("Real Time Clock is running: %v\n", rtc.nextTick)
		rtc.SetPinBool("default_rtc", rtc.curStatus)
		rtc.curStatus = !rtc.curStatus
		rtc.nextTick = rtc.nextTick.Add((time.Second / time.Duration(rtc.Frequency*2)))
	}
}

func (rtc *RealTimeClock) Start(ctx context.Context) error {
	rtc.nextTick = time.Now()
	fmt.Printf("Real Time Clock is running: %v\n", rtc.Frequency)
	return nil
}
